package net.caixiaomi.info.shopkeeper;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;

import net.caixiaomi.info.R;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.BaseAlertDialog;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.CommonEvent;
import net.caixiaomi.info.model.UserInfoModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.login.ForgetPasswordActivity;
import net.caixiaomi.info.ui.login.RegistActivity;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.EventWhat;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.widgets.DefLoading;
import net.caixiaomi.info.widgets.InputEditTextWatcher;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * Created by mac on 2018/11/14.
 */

public class ShopLoginActivity extends BaseActivity implements TextWatcher{
    @BindView(R.id.phone)
    EditText mPhone;
    @BindView(R.id.password)
    EditText mPassword;
    @BindView(R.id.btn_forget_pw)
    View mBtnForgetPW;
    @BindView(R.id.phone_state)
    View mPhoneState;
    @BindView(R.id.lock_state)
    View mLockState;
    @BindView(R.id.divider)
    View mDivider;
    @BindView(R.id.action_divider)
    View mPWDivider;
    @BindView(R.id.pw_container)
    View mPwParent;
    @BindView(R.id.title)
    TextView mTitleTv;

    private boolean isMessageLogin = false;


    @OnClick(R.id.btn_login)
    void toLogin() {
        AppHelper.hideKeyboard(getCurrentFocus());
        String phone = mPhone.getText().toString().trim();
        String password = mPassword.getText().toString().trim();
        if (!AppHelper.checkPhoneAvailable(phone)) {
            ToastUtil.s(R.string.C_PHONE_INVALID);
            return;
        }

            if (!AppHelper.checkPwdAcailable(password)) {
                ToastUtil.s(R.string.C_PASSWORD_INVALID);
                return;
            }


        JSONObject params = new JSONObject();
        params.put("loginSource", "1");
        params.put("mobile", phone);
        params.put("password", password);
        params.put("pushKey", CommonApp.STORE.getString(Constants.KEY_PUSH_CLIENT_ID,""));

        AppHelper.sendStatistics(isMessageLogin ? "yzmdldenglu" : "denglu", new String[]{getString(R.string.C_TERMINAL)}, new String[]{Build.BRAND});
        mLoading.show();
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<UserInfoModel>> login =requestService.loginByPassXN(params);
//        Call<BaseCallModel<UserInfoModel>> login = isMessageLogin ? requestService.loginBySms(params) : requestService.loginByPass(params);
        login.enqueue(new ResponseCallback<BaseCallModel<UserInfoModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<UserInfoModel> data) {
                mLoading.dismiss();
                UserInfoModel userInfoModel = data.data;
                CommonApp.setUserInfo(userInfoModel);
                EventBus.getDefault().post(new CommonEvent(EventWhat.EVENT_LOGIN));
            }

            @Override
            public void onFail(ResponseError error) {
                mLoading.dismiss();ToastUtil.s(error.getMessage());
//                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
//                    ToastUtil.s(error.getMessage());
//                }
            }

            @Override
            public void onError() {
                mLoading.dismiss();
            }
        });
    }

    @OnClick(R.id.btn_forget_pw)
    void toForgetPW() {
        AppHelper.sendStatistics("wangjimima");
        Intent intent = new Intent(this, ShopSetPassActivity.class);
        startActivityForResult(intent,1001);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        finish();
    }

    @Override
    protected int layout() {
        return R.layout.shop_login_layout;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
    }

    private void initView() {
        try {
            mTitleTv.setText("订单出票系统");
            mLoading = new DefLoading(this);
            mPhone.addTextChangedListener(this);
            mPhone.setHint("请输入账号");
            mPassword.setHint("请输入密码");
            mPassword.addTextChangedListener(new InputEditTextWatcher(mLockState));

            //手机号限制11位
            mPhone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});

            mPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AppHelper.sendStatistics(isMessageLogin ? "yzmdlshushoujihao" : "dlshushouji");
                }
            });
            mPassword.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AppHelper.sendStatistics("dlshumima");
                }
            });
            setState();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 正常登录与短信登录UI显示
     */
    private void setState() {
        try {
            mPassword.setText("");
            mBtnForgetPW.setVisibility(isMessageLogin ? View.GONE : View.VISIBLE);
            mDivider.setVisibility(isMessageLogin ? View.VISIBLE : View.GONE);
            mPwParent.setVisibility(isMessageLogin ? View.GONE : View.VISIBLE);
            mPWDivider.setVisibility(isMessageLogin ? View.GONE : View.VISIBLE);
//            StringBuilder stringBuilder = new StringBuilder();
////            stringBuilder.append(getString(R.string.app_name)).append(" · ").append(getString(isMessageLogin ? R.string.C_LOGIN_BY_MESSAGE : R.string.C_LOGIN_BY_PW));
//            stringBuilder.append((getString(isMessageLogin ? R.string.C_LOGIN_BY_MESSAGE : R.string.C_LOGIN_BY_PW)));
//            changeTitle(stringBuilder.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        AppHelper.sendStatistics(isMessageLogin ? "yzmdlfanhui" : "dlfanhui");
        super.onBackPressed();
        setResult(ShopKeeperActivity.LOGIN_CODE);
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onPostEvent(CommonEvent event) {
        switch (event.getWhat()) {
            case EventWhat.EVENT_LOGIN:
                super.onBackPressed();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String text = s.toString().trim();
        mPhoneState.setSelected(!TextUtils.isEmpty(text));
    }

    @Override
    public void afterTextChanged(Editable s) {

    }


}
